package com.xcity.db.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.xcity.game.assist.AssistBuild;
import com.xcity.game.assist.AssistInvite;
import com.xcity.game.assist.AssistManager;

import naga.x.util.StringUtils;

public class AssistsTypeHandler extends BaseTypeHandler<AssistManager> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, AssistManager parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, parameter != null? parameter.toString() : "[]");
	}

	@Override
	public AssistManager getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parse(rs.getString(columnName));
	}

	@Override
	public AssistManager getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parse(rs.getString(columnIndex));
	}

	@Override
	public AssistManager getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parse(cs.getString(columnIndex));
	}

	public static AssistManager parse(String json){
		if(StringUtils.isEmpty(json)){
			return new AssistManager(null, null);
		}
//		String[] strs = StringUtils.split(json, ";");
//		List<AssistInvite> invitList = null;
//		if(strs.length > 1){
////			invitList = JSON.parseArray(strs[1], AssistInvite.class);
//		}
		List<AssistBuild> buildList = JSON.parseArray(json, AssistBuild.class);
		return new AssistManager(null, buildList);
	}
}
